package com.dwjm.shop.goods;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/allGoods")
public class AllGoodsController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        GoodDao goodDao = new GoodDaoImpl();
        int page = 1;
        int size = 10;
        try {
            if (req.getParameter("page") != null) {
                page = Integer.parseInt(req.getParameter("page"));
            }
            if (req.getParameter("size") != null) {
                size = Integer.parseInt(req.getParameter("size"));
            }
        } catch (Exception e) {
            // 参数异常默认第一页
        }
        List<Goods> goodsList = goodDao.findAllGoods(page, size);
        int total = goodDao.countGoods();
        StringBuilder sb = new StringBuilder();
        sb.append("{\"total\":").append(total).append(",\"data\":");
        sb.append("[");
        for (int i = 0; i < goodsList.size(); i++) {
            Goods g = goodsList.get(i);
            sb.append("{\"id\":").append(g.getId())
              .append(",\"title\":\"").append(g.getTitle()).append("\"")
              .append(",\"price\":").append(g.getPrice())
              .append(",\"description\":\"").append(g.getDescription()).append("\"")
              .append(",\"img\":\"").append(g.getImg()).append("\"")
              .append(",\"state\":").append(g.getState())
              .append(",\"mid\":").append(g.getMid())
              .append("}");
            if (i != goodsList.size() - 1) sb.append(",");
        }
        sb.append("]}");
        resp.getWriter().write(sb.toString());
    }
}